﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Janus.BaseEntitys;

namespace Janus.Cores
{
    public static class EnumHelper
    {
        public static SelectList ToSelectListText<TEnum>(object selectedValue = null)
        {
            var result = new SelectList(ToDictionary<TEnum>(), "Value", "Value", selectedValue);
            return result;
        }

        public static SelectList ToSelectList<TEnum>(object selectedValue = null)
        {
            var result = new SelectList(ToDictionary<TEnum>(), "Key", "Value", selectedValue);
            return result;
        }


        public static Dictionary<Int32, String> ToDictionary<TEnum>()
        {
            return Enum.GetValues(typeof(TEnum))
                .Cast<int>().OrderBy(c => c)
                .ToDictionary(e => e, e => Enum.GetName(typeof(TEnum), e));
        }

        public static Dictionary<Int32, String> ToDictionaryByName<TEnum>()
        {
            return Enum.GetValues(typeof(TEnum))
                .Cast<int>().OrderBy(c => c)
                .ToDictionary(e => e, e => {
                    Enum enums = ToObject<TEnum>(e) as Enum;
                    return enums.ToName();
                });
        }

        public static T GetCustomAttribute<T>(object obj) where T : class
        {
            T t = default(T);
            t = Attribute.GetCustomAttribute(obj.GetType(), typeof(T), false) as T;
            return t;
        }

        public static T ToObject<T>(int value)
        {
            var t = (T)Enum.ToObject(typeof(T), value);
            return t;
        }

        public static bool IsDefined<T>(Type enumType, Object value)
        {
            return Enum.IsDefined(typeof(T), value);
        }
    }
}
